package m.jclecai.com.adapter.holder;

import android.content.Context;
import android.support.annotation.LayoutRes;
import android.support.v4.content.ContextCompat;
import android.text.Html;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import m.jclecai.com.R;
import m.jclecai.com.bean.ZqItem;
import m.jclecai.com.dialog.JclqHHDialog;
import m.jclecai.com.listener.MyNotifyTextViewSetChanged;
import m.jclecai.com.listener.OnSclestListener;
import m.jclecai.com.utils.Utils;
import m.jclecai.com.utils.http.FastOk;

/**
 * Created by ZD on 2017/5/6.
 */

public class BetJclqHolder extends ViewHolder implements View.OnClickListener {
    @BindView(R.id.betting_item_delete)
    ImageView bettingItemDelete;
    @BindView(R.id.home_team_name)
    TextView homeTeamName;
    @BindView(R.id.jclq_fen_name)
    TextView jclqFenName;
    @BindView(R.id.away_team_name)
    TextView awayTeamName;
    @BindView(R.id.ll)
    LinearLayout ll;
    @BindView(R.id.tv_lottery)
    CheckBox tvLottery;
    @BindView(R.id.llspf)
    LinearLayout llspf;
    @BindView(R.id.iv_split)
    ImageView ivSplit;
    @BindView(R.id.betting_item_parent)
    LinearLayout bettingItemParent;
    @BindView(R.id.cb_dan)
    public CheckBox cb_dan;

    //这里是混投的
    @BindView(R.id.ll_hun_tou)
    LinearLayout mLlHunTou;
    //这里是胜负
    @BindView(R.id.ll_hun_tou_spf)
    LinearLayout mLlHunTouSfp;

    @BindView(R.id.ll_hun_tou_rqspf)
    LinearLayout mLlHunTouRSfp;

    @BindView(R.id.ll_hun_tou_dxf)
    LinearLayout mLlHunTouDxf;

    @BindView(R.id.cb_hun_tou_more)
    CheckBox mCbHunTouMore;

    MyNotifyTextViewSetChanged change;

    ZqItem mItem;
    int mPosition = 0;
    //记录点击的数据
    Map<String, Map<String, String>> cMap;
    MyNotifyTextViewSetChanged changed;
    int pager = 0;
    private DefaultPresenter mDefaultPresenter;
    private HunTouPresenter mHunTouPresenter;
    private DgPresenter mDgPresenter;
    private SpfPresenter mSpfPresenter;
    String[] codes;

    public BetJclqHolder(Context context, @LayoutRes int resource) {
        super(context, resource);
    }

    private void init() {
        init(this.mItem, pager, mPosition);
    }

    public void init(ZqItem item, int pager, int position) {
        this.pager = pager;
        this.mPosition = position;
        this.mItem = item;
        codes = mItem.getCodes();
        //左边队名-公共属性
        homeTeamName.setText(codes[4]);
        //右边队名-公共属性
        awayTeamName.setText(codes[3]);
        //初始化，全部设置为隐藏；
        tvLottery.setVisibility(GONE);
        llspf.setVisibility(GONE);
        mLlHunTou.setVisibility(GONE);

        cb_dan.setChecked(item.isDan_select());

        mDefaultPresenter = new DefaultPresenter();
        mHunTouPresenter = new HunTouPresenter();
        mDgPresenter = new DgPresenter();
        mSpfPresenter = new SpfPresenter();

        if (pager == 0 || pager == 1 || pager == 2) {
            mSpfPresenter.init(item);
        } else if (pager == 3 || pager == 5) {
            mHunTouPresenter.init(item);
        } else {
            mDefaultPresenter.init(item);
        }
   /*     if (pager > 2) {
            tvLottery.setVisibility(VISIBLE);
            resetCheckBoxStatus(tvLottery, "点击选择比分");
        } else {
            llspf.setVisibility(VISIBLE);
            List<String[]> list = FastOk.getList(codes[15], String[].class);
            initView(list);
        }*/
    }


    /**
     * 解析tag参数
     *
     * @param tag
     * @return
     */
    boolean isCheckThisView(String tag, String index) {
        if (this.mItem.getMap() == null) return false;
        if (this.mItem.getMap().get(index) != null) {
            return this.mItem.getMap().get(index).get(tag) != null;
        }
        return false;
    }

    //显示纯文本
    String showTextUi() {
        //到时候这个排序可以提到外面去 减少计算时间
        Map<String, Map<String, String>> map = mItem.getMap();
        //将key 排序然后显示
        StringBuilder sb = new StringBuilder();
        for (Map<String, String> strMap : map.values()) {
            //勾选的数据 "0_spf_0_2.25_胜" -> "0_spf_0_2.25_胜"
            // 0-服务器数据下标，spf 类型 0-点击的下标用来排序 2.25倍数 胜显示的值
            String[] strs = strMap.keySet().toArray(new String[]{});
            int[] arrayKey = new int[strs.length];
            Map<Integer, String> nMap = new HashMap<>();
            //排序
            for (int j = 0; j < strs.length; j++) {
                String[] split = strs[j].split("_");
                arrayKey[j] = Integer.parseInt(split[2]);
                nMap.put(arrayKey[j], strs[j]);
            }
            Arrays.sort(arrayKey);
            //输出
            for (int j = 0; j < arrayKey.length; j++) {
                String keys = nMap.get(arrayKey[j]);
                String[] split = keys.split("_");
                /*if (("rfsf").equals(split[1]))
                    sb.append("让");
                sb.append(split[4]);
                if ("jqs".equals(split[1]))
                    sb.append("球");*/
                if ("sfc".equals(split[1])) {
                    sb.append(split[4]);
                    sb.append(" ");
                }
            }
        }
        return sb.toString();
    }

    //混投点击更多玩法
    @OnClick(R.id.tv_lottery)
    void more(View v) {
        execCheckParam((CheckBox) v, "点击选择比分");
    }

    /**
     * 处理选中的数据与ui交互
     *
     * @param cb
     * @param buttonText
     */
    void execCheckParam(final CheckBox cb, final String buttonText) {
        resetCheckBoxStatus(cb, buttonText);
      /*  JczqHHDialog dialog = new JczqHHDialog(getContext(), this.mItem.getCodes(), this.mItem.getMap(), JczqHHDialog.JCZQSHOWTYPE.SHOWSFC);
        dialog.setListener(new OnSclestListener() {
            @Override
            public void sure(Map<String, Map<String, String>> map) {
                if (mItem.getMap() != null) {
                    if (map.size() > 0) {
                        for (String key : map.keySet()) {
                            mItem.getMap().put(key, map.get(key));
                        }
                    } else {
                        //胜分差的下标
                        mItem.getMap().remove("5");
                    }
                } else if (mItem.getMap() == null && map.size() > 0) {
                    mItem.setMap(map);
                }
                String desc = showTextUi();
                cb.setText(desc);
                cb.setChecked(!buttonText.equals(desc));
                init();
                statistics();
            }
       });*/

        JclqHHDialog.JCZQSHOWTYPE type = JclqHHDialog.JCZQSHOWTYPE.SHOWSFC;
        if (pager == 3) {
            type = JclqHHDialog.JCZQSHOWTYPE.SHOWHUNTOU;
        }

        JclqHHDialog dialog = new JclqHHDialog(getContext(), this.mItem.getCodes(), this.mItem.getMap(), type);
        dialog.setListener(new OnSclestListener() {
            @Override
            public void sure(Map<String, Map<String, String>> map) {

                //要做的一个操作就不能是这个了；
                if (map == null || map.size() <= 0) {
                    delete();
                    return;
                }

                if (mItem.getMap() != null) {
                    mItem.setMap(map);
                }
                String desc = showTextUi();
                cb.setText(desc);
                cb.setChecked(!buttonText.equals(desc));
                init();
                statistics();
            }
        });
        dialog.show();
    }

    //重置投注按钮状态(CheckBox)
    void resetCheckBoxStatus(final CheckBox cb, final String buttonText) {
        //设置默认选中
        String desc = mItem.getMap() != null && mItem.getMapLength() > 0 ? showTextUi() : buttonText;
        cb.setText(desc);
        cb.setChecked(!buttonText.equals(desc));
    }

    //分割线
    public void isShowSplit(boolean show) {
        ivSplit.setVisibility(show ? VISIBLE : GONE);
    }

    @Override
    public void onClick(View v) {

        checkButtonDoClick(v);

    }

    private void checkButtonDoClick(View v) {

        if (mItem.getMap() == null) {
            cMap = new HashMap<>();
            mItem.setMap(cMap);
        } else {
            cMap = mItem.getMap();
        }
        String tag = v.getTag().toString();
        String key = tag.substring(0, 1);
        String value = tag;
        if (cMap.get(key) != null) {
            //有则删除 无则添加 - 等同于没选中则选中 选中了则取消
            if (cMap.get(key).get(value) != null) {
                cMap.get(key).remove(value);
            } else {
                cMap.get(key).put(value, value);
            }
        } else {
            Map<String, String> map = new HashMap<>();
            map.put(value, value);
            cMap.put(key, map);
        }
        if (cMap.get(key) != null && cMap.get(key).values().size() <= 0)
            cMap.remove(key);
        statistics();
    }

    @OnClick(R.id.betting_item_delete)
    void delete() {
        if (Utils.ZQ_ITEM_LIST.contains(mItem)) {
            Utils.ZQ_ITEM_LIST.remove(mItem);
            if (changed != null)
                changed.refreshData();
        }
    }

    //胆码
    @OnClick(R.id.cb_dan)
    void checkDan() {
        mItem.setDan_select(cb_dan.isChecked());
        if (getCheckDan() > Utils.ZQ_ITEM_LIST.size() - 1) {
            cb_dan.setChecked(false);
            mItem.setDan_select(cb_dan.isChecked());
            Toast.makeText(getContext(), "胆码场次超过限制", Toast.LENGTH_SHORT).show();
            return;
        }
        if (change != null)
            change.onClickSetChangedText();
    }

    public int getCheckDan() {
        int checkCount = 0;
        for (int i = 0; i < Utils.ZQ_ITEM_LIST.size(); i++) {
            if (Utils.ZQ_ITEM_LIST.get(i).isDan_select())
                checkCount++;
        }
        return checkCount;
    }

    //统计勾选的数据
    private void statistics() {
        if (mItem.getMapLength() > 0) {
            if (!Utils.ZQ_ITEM_LIST.contains(mItem)) {
                if (mPosition < Utils.ZQ_ITEM_LIST.size())
                    Utils.ZQ_ITEM_LIST.add(mPosition, mItem);
                else
                    Utils.ZQ_ITEM_LIST.add(mItem);
            }
        } else {
            if (Utils.ZQ_ITEM_LIST.contains(mItem)) {
                Utils.ZQ_ITEM_LIST.remove(mItem);
                if (changed != null)
                    changed.refreshData();}
        }
        if (changed != null)
            changed.onClickSetChangedText();
    }

    public void setChangeListener(MyNotifyTextViewSetChanged change) {
        this.changed = change;
    }

    /**
     * 这里是默认的处理方式；
     */
    public class DefaultPresenter {

        public void init(ZqItem item) {
            tvLottery.setVisibility(VISIBLE);
            resetCheckBoxStatus(tvLottery, "点击选择比分");
        }
    }

    /**
     * 这里是胜平负；
     */
    public class SpfPresenter {
        public void init(ZqItem item) {
            llspf.setVisibility(VISIBLE);
            List<String[]> list = FastOk.getList(item.getCodes()[15], String[].class);
            initView(list);
        }

        void initView(List<String[]> strList) {
            //当前采种下面有几种比例选项 llspf
            String[] strings = strList.get(pager);
            if (strings.length > 2)
                strings = new String[]{strings[1], strings[2]};
            for (int i = 0; i < strings.length; i++) {
                CheckBox cb = (CheckBox) llspf.getChildAt(i);
                cb.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        checkButtonDoClick(v);
                    }
                });
                StringBuilder tag = new StringBuilder();
                if (pager == 0) {
                    tag.append("0_sf");
                    tag.append("_" + i + "_" + strings[i]);
                } else if (pager == 1) {
                    tag.append("1_rfsf");
                    tag.append("_" + (i + 1) + "_" + strings[i]);
                } else if (pager == 2) {
                    tag.append("2_dxf");
                    tag.append("_" + (i + 1) + "_" + strings[i]);
                }
                if (pager != 2) {
                    if (i == 1) {
                        cb.setText("主胜" + strings[i]);
                        tag.append("_主胜_3");
                    } else if (i == 0) {
                        cb.setText("客胜" + strings[i]);
                        tag.append("_客胜_0");
                    }

                } else {
                    if (i == 1) {//小分 = 0
                        cb.setText("总分<" + strList.get(pager)[0] + "\n" + strings[0]);
                        // tag.append("_主胜_3");
                        tag.append("_总分<" + strList.get(pager)[0] + "_0");
                    } else if (i == 0) {//大分 = 3
                        cb.setText("总分>" + strList.get(pager)[0] + "\n" + strings[1]);
                        //tag.append("_客胜_0");
                        tag.append("_总分>" + strList.get(pager)[0] + "_3");
                    }

                }
                cb.setTag(tag.toString());
                cb.setChecked(isCheckThisView(cb.getTag().toString(), String.valueOf(pager)));
            }
        }
    }

    /**
     * 这里是混头的Presenter
     */
    public class HunTouPresenter {

        public void init(ZqItem item) {
            mLlHunTou.setVisibility(View.VISIBLE);
            List<String[]> list = FastOk.getList(item.getCodes()[15], String[].class);

            mCbHunTouMore.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    execCheckParam(((CheckBox) v), "点击展开胜分差方案");
                }
            });
            //这里还要初始化胜分差的按钮的内容的；
            String desc = showTextUi();

            if (TextUtils.isEmpty(desc)) {
                mCbHunTouMore.setChecked(false);
                mCbHunTouMore.setText("点击展开胜分差方案");
            } else {
                mCbHunTouMore.setChecked(true);
                mCbHunTouMore.setText(desc);
            }


            //初始化；
            initSPF(list.get(0), mLlHunTouSfp);
            initRQSPF(list.get(1), mLlHunTouRSfp);
            initDXF(list.get(2), mLlHunTouDxf);
        }


        void initSPF(String[] strings, ViewGroup group) {
            //当前采种下面有几种比例选项 llspf 第一个是textview
            for (int i = 0; i < strings.length; i++) {
                CheckBox cb = (CheckBox) group.getChildAt(i + 1);
                cb.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        checkButtonDoClick(v);
                    }
                });
                StringBuilder tag = new StringBuilder("0_sf_" + i + "_" + strings[i]);
                if (i == 1) {
                    //addBlue(cb, "sf");
                    cb.setText(("主胜" + strings[i]));
                    tag.append("_主胜_3");
                } else if (i == 0) {
                    cb.setText(("客胜" + strings[i]));
                    tag.append("_客胜_0");
                }
                cb.setTag(tag.toString());
                cb.setChecked(isCheckThisView(cb.getTag().toString(), "0"));
                cb.setEnabled(true);
                cb.setTextColor(ContextCompat.getColorStateList(getContext(), R.color.black_white_selector));

                float result = -1;
                try {
                    result = Float.parseFloat(strings[i]);
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }

                if (TextUtils.isEmpty(strings[i]) || ((result != -1) && (result == 0)) || (pager == 5 && !isDG("sf"))) {
                    cb.setText("未开售");
                    cb.setEnabled(false);
                    cb.setTextColor(ContextCompat.getColor(getContext(), R.color.b));
                }
            }
        }


        void initRQSPF(String[] strings, ViewGroup group) {
            //当前采种下面有几种比例选项 llrqspf 第一个是textview
            String sf = TextUtils.isEmpty(strings[0]) ? "0" : strings[0];
            String color = Float.valueOf(sf) > 0 ? "#f03d3d" : "#14a514";
            Spanned sp = Html.fromHtml(String.format(getResources().getString(R.string.jczq_fl), "", color, strings[0], ""));
            if (pager != 3)
                awayTeamName.append(sp);
            for (int i = 0; i < strings.length; i++) {
                if (group.getChildAt(i) instanceof CheckBox) {

                    CheckBox cb = (CheckBox) group.getChildAt(i);
                    StringBuilder tag = new StringBuilder("1_rfsf_" + i + "_" + strings[i]);
                    cb.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            checkButtonDoClick(v);
                        }
                    });
                    if (i == 1) {
                        //addBlue(cb, "rfsf");
                        cb.setText(("客胜" + strings[i]));
                        tag.append("_客胜_0");
                    } else if (i == 2) {
                        sp = new SpannableString("主胜" + strings[i]);
                        if (pager == 3)
                            sp = Html.fromHtml(String.format(getResources().getString(R.string.jczq_fl), "主", color, strings[0], "胜" + strings[i]));
                        cb.setText(sp);
                        tag.append("_主胜_3");
                    }
                    cb.setTag(tag.toString());
                    cb.setEnabled(true);
                    cb.setTextColor(ContextCompat.getColorStateList(getContext(), R.color.black_white_selector));
                    if ("0".equals(strings[i]) || TextUtils.isEmpty(strings[i]) || (pager == 5 && !isDG("rfsf"))) {
                        cb.setText("未开售");
                        cb.setEnabled(false);
                        cb.setTextColor(ContextCompat.getColor(getContext(), R.color.b));
                    }
                    cb.setChecked(isCheckThisView(cb.getTag().toString(), "1"));
                }
            }
        }

        void initDXF(String[] strings, ViewGroup group) {
            //当前采种下面有几种比例选项 llrqspf 第一个是textview
            for (int i = 1; i < strings.length; i++) {
                CheckBox cb = (CheckBox) group.getChildAt(i);
                cb.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        checkButtonDoClick(v);
                    }
                });
                StringBuilder tag = new StringBuilder("2_dxf_" + i + "_" + strings[i]);
                if (i == 2) {//小分 = 0
                    cb.setText("总分<" + strings[0] + "\n" + strings[1]);
                    tag.append("_" + "总分<" + strings[0] + "_0");
                } else if (i == 1) {//大分=3
//                    addBlue(cb, "dxf");
                    cb.setText("总分>" + strings[0] + "\n" + strings[2]);
                    tag.append("_" + "总分>" + strings[0] + "_3");
                }
                cb.setTag(tag.toString());
                cb.setChecked(isCheckThisView(cb.getTag().toString(), "2"));
                cb.setEnabled(true);
                cb.setTextColor(ContextCompat.getColorStateList(getContext(), R.color.black_white_selector));
                if ("0".equals(strings[i]) || TextUtils.isEmpty(strings[i]) || (pager == 5 && !isDG("dxf"))) {
                    cb.setText("未开售");
                    cb.setEnabled(false);
                    cb.setTextColor(ContextCompat.getColor(getContext(), R.color.b));
                }
            }
        }

    }

    //支持单关的小蓝点
    boolean isDG(String realtype) {
        int mid = -1;
        boolean itemDgBool;
        switch (realtype) {
            case "sf":
                mid = 3;
                break;
            case "rfsf":
                mid = 2;
                break;
            case "sfc":
                mid = 1;
                break;
            case "dxf":
                mid = 0;
                break;
        }
        int value = TextUtils.isEmpty(codes[18]) ? 0 : Integer.parseInt(codes[18]);
        itemDgBool = ((value & 1 << mid) == (1 << mid));
        return itemDgBool;
    }


    /**
     * 大小分的Presenter
     */
    public class DxfPresenter {
        public void init(ZqItem item) {

        }
    }

    /**
     * 单关的逻辑Presenter
     */
    public class DgPresenter {
        public void init(ZqItem item) {

        }
    }
}
